<!-- 头部/深圳市宝安区治水提质水质动态监测系统 -->
<template>
  <div class="myHeader">
    <div class="logoCnt">
      <!-- <img src="/img/logo.png" alt=""> -->
      <!-- 深圳市宝安区治水提质水质动态监测系统 -->
      <!-- 治水提质水质动态监测系统 -->
      城镇污水管网水质动态监测系统
      <!-- 安志生态河流水质状况监测与评价系统 -->
    </div>
    <div class="headerInfo">
      <div class="timeSet">
        <countdown
          :show="$route.path === '/stationMonitor'"
          :number="5 * 60"
          :timeOutCallback="refreshCurPath"
        ></countdown>
      </div>

      <div class="infoItem emailBox">
        <el-popover
          ref="emailPopover"
          placement="bottom"
          :title="'您有' + emailList.length + '条预警提醒'"
          width="300"
          popper-class="emailPopover"
          trigger="click"
        >
          <div
            v-show="emailList.length > 0"
            style="max-height: 90vh; overflow: auto; padding-right: 15px"
          >
            <div
              v-for="(item, index) of emailList"
              :key="index"
              class="emailTipsClass"
            >
              <p>
                {{ item.station }}在
                <span class="TableWarnRed">{{ item.time }}</span> 出现
                <span class="TableWarnRed">{{ item.type }}</span
                >，请尽快
                <el-button
                  type="text"
                  style="padding: 0"
                  @click="tipsRouter(item)"
                  >查看并处理</el-button
                >！如果已处理，请忽略。
              </p>
            </div>
          </div>
          <div v-show="emailList.length <= 0">
            <p>暂无内容</p>
          </div>
        </el-popover>
        <el-button size="mini" round class="headerBtn" v-popover:emailPopover>
          <el-badge
            size="mini"
            :hidden="emailList.length <= 0"
            :value="emailList.length <= 99 ? emailList.length : '99+'"
          >
            <i class="iconfont iconbell"></i>
          </el-badge>
        </el-button>
      </div>

      <div class="infoItem tipsBox">
        <el-popover
          ref="tipsPopover"
          placement="top"
          title="任务提醒"
          width="280"
          trigger="click"
        >
          <div v-show="tipsList.length > 0">
            <div
              v-for="(item, index) of tipsList"
              :key="index"
              class="emailTipsClass"
            >
              <p>
                任务编号为{{ item.taskId }}, 需要您
                <el-button
                  type="text"
                  style="padding: 0"
                  @click="tipsRouter(item)"
                  >去完成</el-button
                >！！
              </p>
            </div>
          </div>
          <div v-show="tipsList.length <= 0">
            <p>暂无内容</p>
          </div>
        </el-popover>
        <el-button size="mini" round class="headerBtn" v-popover:tipsPopover>
          <el-badge is-dot :hidden="tipsList.length <= 0">
            <i class="iconfont iconemail"></i>
          </el-badge>
        </el-button>
      </div>

      <div class="infoItem" @click="feedbackVisible = true">
        <floatBtn />
      </div>

      <el-dropdown trigger="click" @command="handleCommand">
        <span
          class="avatarBtn"
          :style="{ lineHeight: userInfo.user.photo ? '66px' : '50px' }"
        >
          <img
            v-if="userInfo.user.photo"
            class="avatarPhoto"
            :src="
              'http://47.112.16.168:' + userInfo.user.photo.split(',').shift()
            "
            alt
          />
          <i v-else class="iconfont icontouxiang avatar"></i>
          <i class="el-icon-caret-bottom" />
        </span>
        <el-dropdown-menu slot="dropdown" class="userInfo">
          <el-dropdown-item disabled style="text-align: center"
            >用户名：{{ userInfo.user.username }}</el-dropdown-item
          >
          <el-dropdown-item divided command="warningWayClick">
            <p style="text-align: center">预警方式设置</p>
          </el-dropdown-item>
          <el-dropdown-item divided command="stationSelectClick">
            <p style="text-align: center">点位选择设置</p>
          </el-dropdown-item>
          <el-dropdown-item divided command="operationNoticeClick">
            <p style="text-align: center">运维周期提醒</p>
          </el-dropdown-item>
          <el-dropdown-item divided command="openUpdateCnt">
            <p style="text-align: center">修改密码</p>
          </el-dropdown-item>
          <el-dropdown-item divided command="loginOut">
            <p style="text-align: center">退出登陆</p>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>

    <el-dialog
      :visible.sync="updatePassWordVisible"
      custom-class="updataPw"
      :append-to-body="true"
    >
      <div slot="title">
        <p class="updataPwTitle">修改密码</p>
      </div>
      <el-form
        :model="updatePassWordForm"
        :rules="updateFormRules"
        ref="updatePassWordForm"
        size="small"
        label-width="80px"
        v-loading="updatePassWordLoading"
        style="width: 60%; margin: 0 auto"
      >
        <el-form-item label="账号" prop="account">
          <el-input
            v-model="updatePassWordForm.account"
            placeholder="请输入账号"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="updatePassWordForm.phone"
            placeholder="请输入手机号"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="身份证" prop="identity">
          <el-input
            v-model="updatePassWordForm.identity"
            placeholder="请输入身份证"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input
            v-model="updatePassWordForm.oldPassword"
            placeholder="请输入旧密码"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="updatePassWordForm.newPassword"
            placeholder="请输入新密码"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          class="greenBtn"
          size="mini"
          @click="updatePassword"
          >提交</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapMutations, mapActions } from "vuex";
import storage from "@/plugins/localStorage";
import { socketUrl } from "../plugins/url";
import floatBtn from "@/components/floatBtn";
import countdown from "@/components/countdown";
export default {
  name: "myHeader",
  components: {
    floatBtn,
    countdown,
  },
  data() {
    return {
      msg: "hello myHeader",
      timer: null,
      roleVisible: false,
      updatePassWordVisible: false,
      updatePassWordLoading: false,
      updatePassWordForm: {
        account: "",
        phone: "",
        identity: "",
        oldPassword: "",
        newPassword: "",
      },
      updateFormRules: {
        account: [
          {
            required: true,
            message: "请输入账号",
            trigger: "blur",
          },
        ],
        phone: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
        ],
        identity: [
          {
            required: true,
            message: "请输入身份证",
            trigger: "blur",
          },
        ],
        oldPassword: [
          {
            required: true,
            message: "请输入旧密码",
            trigger: "blur",
          },
        ],
        newPassword: [
          {
            required: true,
            message: "请输入新密码",
            trigger: "blur",
          },
        ],
      },

      socketList: [],
    };
  },
  created() {
    // debugger

    // let that = this

    // let socketUrl = 'ws://47.112.16.168:8802/websocket/'
    // let socketUrl = 'ws://192.168.50.151:8802/websocket/'
    // let socketUrl = 'ws://192.168.50.77:8802/websocket/'
    let myWebsocket = new WebSocket(socketUrl + this.userInfo.user.account);
    // myWebsocket = new WebSocket(socketUrl)
    myWebsocket.onopen = function () {
      console.log("header链接成功 ");
      myWebsocket.send("task");
      myWebsocket.send("warn/pc");
    };
    myWebsocket.onerror = function (event) {
      console.error("header链接失败:", event);
    };
    myWebsocket.onmessage = async (event) => {
      if (event.data === "nameList update") {
        await this.getStationListName({ dataType: null });
      }
      this.socketList.push(JSON.parse(event.data));
    };
    this.startHandle(this.socketList);
  },
  methods: {
    ...mapActions(["putUpdatePassword", "doLoginOut", "getStationListName"]),
    ...mapMutations([
      "pushHeaderTips",
      "resetHeaderTips",
      "delOnceHeaderTips",

      "pushHeaderEmail",
      "resetHeaderEmail",
      "delOnceHeaderEmail",

      "changeOnlineCarSatatus",

      // "refreshCurPath"
    ]),
    handleCommand(command) {
      // command 设定为 function name
      this[command]();
    },
    async loginOut() {
      this.roleVisible = false;
      let flag = confirm("你确定要退出登录吗?");
      if (flag) {
        await this.doLoginOut(this.userInfo.user.userId);
        storage.reload();
        this.resetHeaderTips();
        this.resetHeaderEmail();
        this.$router.push("/login");
      }
    },
    tipsRouter(item) {
      if (
        item.opitons.query.waterStation &&
        this.$route.query.waterStation === item.opitons.query.waterStation
      ) {
        return this.$notify({
          type: "info",
          title: "提示",
          message: "预警水站为当前筛选水站！",
        });
      }
      this.$router.push(item.opitons);
    },
    warningWayClick() {
      this.$router.push("/warningWay");
    },
    stationSelectClick() {
      this.$router.push("/stationSelect");
    },
    operationNoticeClick() {
      this.$router.push("/cycleSettings");
    },
    openUpdateCnt() {
      this.updatePassWordForm.account = this.userInfo.user.account;
      this.updatePassWordVisible = true;
    },
    updatePassword() {
      this.$refs["updatePassWordForm"].validate(async (valid) => {
        if (valid) {
          this.updatePassWordLoading = true;
          let updatePassWordForm = this.updatePassWordForm;
          let result = await this.putUpdatePassword(updatePassWordForm);
          if (result.message !== "success") {
            this.$notify({
              type: "warning",
              title: "提示",
              message: result.info,
            });
          } else {
            this.$notify({
              type: "success",
              title: "成功",
              message: "修改成功！！",
            });
            this.$refs["updatePassWordForm"].resetFields();
            this.updatePassWordVisible = false;
          }
          this.updatePassWordLoading = false;
        } else {
          return false;
        }
      });
    },
    olderHandel2(message) {
      let opitons;
      let warningTypes = [
        "因子超标预警",
        "设备异常预警",
        "数据因子缺失",
        "数据丢失",
        "设备离线",
        "分钟数据预警",
      ];
      if (warningTypes.includes(message.type)) {
        opitons = {
          path: "/warningAdmin",
          query: {
            waterStation: message.station,
            warningType: message.type,
          },
        };
        message.opitons = opitons;
        this.pushHeaderEmail(message);
        return;
      }
      // if(message.type === '分钟数据预警') {
      //   opitons = {path: '/warningAdmin', query: {waterStation: message.station,warningType: message.type}}
      //   message.opitons = opitons
      //   this.pushHeaderEmail(message)
      //   return
      // }
      // if(message.type === '设备异常预警') {
      //   opitons = {path: '/warningAdmin', query: {waterStation: message.station}}
      //   message.opitons = opitons
      //   this.pushHeaderEmail(message)
      //   return
      // }
      // if(message.type === 'offline') { //设备离线预警
      //   opitons = {path: '/warningAdmin', query: {waterStation: message.waterstation, warningType: "水站设备离线"}}
      //   message.opitons = opitons
      //   this.pushHeaderEmail(Object.assign({}, message, {content: message.systemName + "设备离线", time: message.datatime}) )
      //   return
      // }
      if (message.type === "inspect") {
        opitons = {
          path: "/contentPlot",
          query: {
            type: message.type,
            taskId: message.taskId,
            station: message.station,
          },
        };
        message.opitons = opitons;
        this.pushHeaderTips(message);
        return;
      }
      if (message.type === "maintenance") {
        opitons = {
          path: "/contentPlot",
          query: {
            type: message.maintenance,
            taskId: message.taskId,
          },
        };
        message.opitons = opitons;
        this.pushHeaderTips(message);
        return;
      }
      if (message.type === "mobile") {
        opitons = {
          path: "/mobileMonitor/overview/input",
          query: {
            taskId: message.taskId,
          },
        };
        message.opitons = opitons;
        this.pushHeaderTips(message);
        return;
      }
      if (message.type === "point" || message.type === "jingwei") {
        return;
      }
      if (message.type === "routingFinish") {
        // 实时监测车线路结束
        this.changeOnlineCarSatatus(false);
        return;
      }
    },
    debounce(fn, wait) {
      var timer = null;
      return function () {
        var context = this;
        var args = arguments;
        if (timer) {
          clearTimeout(timer);
          timer = null;
        }
        timer = setTimeout(function () {
          fn.apply(context, args);
        }, wait);
      };
    },
    startHandle(data) {
      this.timer = setInterval(() => {
        if (data.length > 0) {
          this.olderHandel2(data.shift());
        }
      }, 500);
    },
    refreshCurPath() {
      console.log(this.$route.path);
      this.$router.replace({
        path: this.$router.path,
        query: {
          a: new Date().getTime(),
        },
      });
    },
  },
  computed: {
    ...mapGetters({
      userInfo: "getUserInfo",
      tipsList: "getTipsList",
      emailList: "getEmailList",
    }),
  },
};
</script>

<style scoped>
.myHeader {
  position: fixed;
  left: 0;
  top: 0;
  height: 50px;
  display: flex;
  flex-direction: row;
  width: 100%;
  height: 50px;
  line-height: 50px;
  background-color: #363a43;

  background-image: linear-gradient(90deg, #4eb2ff 0%, #0b69cb 100%),
    linear-gradient(#1e87f0, #1e87f0);
  background-blend-mode: normal, normal;
  box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.1);

  color: #fff;
  z-index: 9;
}

.logoCnt {
  font-size: 20px;
  line-height: 50px;
  padding: 0 12px;
}

.headerInfo {
  display: flex;
  flex-direction: row;
  margin-left: auto;
  padding-right: 20px;
}

.headerInfo .infoItem {
  margin-right: 18px;
}

.headerInfo .timeInfo {
  margin-right: 5px;
}

.headerInfo .position {
  margin-right: 25px;
}

.emailTipsClass {
  border-bottom: 1px solid #eee;
  margin-bottom: 12px;
  padding-bottom: 12px;
  line-height: 26px;
}

.emailTipsClass:last-child {
  border-bottom: none;
}

.headerInfo .headerBtn {
  height: 100%;
  padding: 4px 5px;
  background: transparent;
  border-color: transparent;
  color: #ffffff;
}

.headerImg {
  text-align: center;
}

.headerImg img {
  max-width: 120px;
}

.userInfo {
  padding: 10px;
}

.iconbell,
.iconemail {
  font-size: 18px;
}

.avatarBtn {
  color: #fff;
  height: 50px;
  /* line-height: 66px; */
  cursor: pointer;
}

.avatarBtn .avatarPhoto {
  width: 30px;
  height: 30px;
  border-radius: 50%;
}

.avatarBtn .avatar {
  font-size: 24px;
}

.timeSet {
  padding-top: 2px;
  font-size: 12px;
  margin-right: 50px;
}
</style>
<style>
.userInfo .el-dropdown-menu__item.is-disabled {
  color: #666;
}

.emailPopover.el-popper {
  top: 38px !important;
}
</style>
